<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    draggable
    :loading="loading"
    width="1400px"
    @close="onClose"
  >
    <div class="box">
      <miniPage :formParams="formParams" />
      <div style="margin-left: 50px">
        <div class="title">基本信息</div>
        <el-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-position="right"
          label-width="auto"
          :disabled="isDisabled"
        >
          <el-form-item label="活动名称" prop="name">
            <el-input
              v-model.trim="formParams.name"
              placeholder="最多10个字符"
              maxlength="10"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="有效日期" prop="dateRange">
            <div>
              <el-date-picker
                v-model="formParams.dateRange"
                type="datetimerange"
                range-separator="~"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                date-format="YYYY-MM-DD"
                time-format="HH:mm"
                :disabled-date="disabledDate"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 440px"
              />
            </div>
          </el-form-item>
          <el-form-item label="背景图" prop="activityImg">
            <div>
              <ImageUploadByType
                v-model="formParams.activityImg"
                uploadType="1"
                :isShowTip="false"
                :limit="1"
                :fileSize="10"
                :imagePx="[750, 516]"
              />图片的比例750px*516px请上传 大小不超过 10MB 格式为 png/jipg/jpeg 的文件</div
            >
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model.trim="formParams.remarks"
              placeholder="最多10个字符"
              maxlength="10"
              clearable
              style="width: 240px"
            />
          </el-form-item>

          <div class="el-form-item__label">首次充值奖励 </div>
          <div class="_line">
            <span>赠送消费金额</span> <span style="margin: 0 0 0 90px">额外储值权益</span>
          </div>
          <div style="margin: 0 0 10px 10px">
            <el-form-item>
              <el-input
                v-model="formParams.first.credits"
                placeholder="请输入"
                clearable
                :min="1"
                style="width: 150px"
                @input="(val) => handleNumber(val)"
              />
              &nbsp; &nbsp; &nbsp; &nbsp;
              <el-button link type="primary" @click="handleAddCoupons(true)">{{
                couponInfo?.marCouponCount && couponInfo?.couponName
                  ? `${couponInfo.couponName}*${couponInfo.marCouponCount}`
                  : '添加优惠券'
              }}</el-button>
            </el-form-item>
          </div>
          <div class="el-form-item__label">储值金额设置（最多6条）</div>
          <el-table class="table-box" :data="formParams?.svadList">
            <el-table-column label="储值金额" width="150px" align="center">
              <template #default="scope">
                <el-form-item prop="money">
                  <el-input
                    v-model="scope.row.money"
                    placeholder="请输入"
                    clearable
                    style="width: 100%"
                    @blur="handleBlur(scope.$index, 'money')"
                    @input="(val) => handleNumber(val, scope.$index, 'money')"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="赠送消费金额" width="150px" align="center">
              <template #default="scope">
                <el-form-item prop="giftGold" label-width="auto">
                  <el-input
                    v-model="scope.row.giftGold"
                    placeholder="请输入"
                    clearable
                    @input="(val) => handleNumber(val, scope.$index, 'giftGold')"
                    style="width: 100%"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="额外储值权益" width="150px" align="center">
              <template #default="scope">
                <el-form-item prop="extraCoupons" label-width="auto">
                  <el-button
                    style="width: 100%"
                    link
                    type="primary"
                    @click="handleAddCoupons(false, scope.row, scope.$index)"
                    >{{
                      scope.row.couponName && scope.row.marCouponCount
                        ? `${scope.row.couponName}*${scope.row.marCouponCount}`
                        : '添加优惠券'
                    }}</el-button
                  >
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="活动标签" width="150px" align="center">
              <template #default="{ row }">
                <el-form-item prop="activityTag">
                  <el-input
                    v-model="row.activityTag"
                    placeholder="最多3个字符"
                    clearable
                    maxlength="3"
                    style="width: 100%"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="额外储值标签" width="200px" align="center">
              <template #default="{ row }">
                <el-form-item prop="extraStoredTag">
                  <el-input
                    v-model="row.extraStoredTag"
                    placeholder="最多6个字符"
                    clearable
                    maxlength="6"
                    style="width: 100%"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="&nbsp;" align="center" fixed="right" width="80">
              <template #default="scope">
                <el-button @click="controlList('delete', scope.$index)"
                  ><el-icon><Remove /></el-icon
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="display: flex; justify-content: center; margin: 10px 0 0">
            <el-button v-show="addButton" icon="Plus" @click="controlList('add')"> 添加 </el-button>
          </div>
        </el-form>
      </div>
    </div>

    <couponList ref="couponListRef" @select="handleSelect" />

    <template #footer>
      <el-button v-show="!isDisabled" type="primary" @click="handleAction(true)"> 保存 </el-button>
      <el-button v-show="!isDisabled" @click="handleAction(false)">取消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import miniPage from './miniPage'
import couponList from './couponList.vue'
import { postStoredAddApi, getStoredDetailsApi } from '@/api/storedEquity'
import { deepClone } from '@/utils'

const { proxy } = getCurrentInstance()

const visible = ref(false)
const loading = ref(false)
const formParams = ref({
  name: null,
  remarks: null,
  activityImg: null,
  svadList: [],
  first: {
    credits: null,
    couponInfo: null
  },
  dateRange: null
})
const isDisabled = ref(false)
const addButton = computed(() => formParams.value.svadList?.length < 6)
const couponInfo = computed(() => formParams.value.first.couponInfo)
const rules = ref({
  name: [{ required: true, message: '请输入活动名称，且不超过10个字符', trigger: 'blur' }],
  dateRange: [{ required: true, message: '请输入选择有效日期', trigger: 'blur' }],
  activityImg: [{ required: true, message: '请选择背景图', trigger: 'change' }]
})
const formRef = ref()
const couponListRef = ref()
function init(row, type) {
  if (type === 'details') {
    isDisabled.value = true
    loading.value = true
    console.log(row)
    getStoredDetailsApi(row.id)
      .then((res) => {
        if (res?.data) {
          formParams.value = { ...formParams.value, ...deepClone(res?.data) }
          formParams.value.dateRange = [formParams.value?.startTime, formParams.value?.endTime]
          const first = formParams.value.svadList?.find((i) => i.type === 1)
          formParams.value.svadList = formParams.value.svadList
            ?.filter((i) => i.type !== 1)
            .map((i, index) => ({ ...i, id: index }))
          if (first) {
            const { giftGold, ...i } = first
            formParams.value.first.credits = first?.giftGold
            formParams.value.first.couponInfo = i
            console.log(formParams.value)
          }
        }
      })
      .finally(() => {
        loading.value = false
      })
  } else {
    isDisabled.value = false
  }
  visible.value = true
}
function handleNumber(val, index, type) {
  console.log(val, index, type)
  val = val.replace(/[^0-9]/g, '').replace(/^0+/, '')
  if (index >= 0) {
    formParams.value.svadList[index][type] = val
    if (+formParams.value.svadList[index].money < +formParams.value.svadList[index].giftGold) {
      formParams.value.svadList[index].giftGold = formParams.value.svadList[index].money
      ElMessage.warning('赠送金额不能超过对应的储值金额')
    }
  } else {
    formParams.value.first.credits = val
  }
}

function handleBlur(index, type) {
  formParams.value.svadList.forEach((v, i, a) => {
    console.log('=====')
    if (index != i && formParams.value.svadList[index].money === v.money) {
      formParams.value.svadList[index].money = null
      ElMessage.warning('充值金额不能重复')
    }
    console.log(v, i, a, index)
  })
}
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}
/**是否是选中的首冲优惠券 */
function handleSelect(item, type, selectedIndex) {
  if (type) {
    formParams.value.first.couponInfo = {
      type: 1,
      marCouponId: item.id,
      couponName: item.couponName,
      marCouponCount: item.couponCount
    }
  } else if (selectedIndex >= 0) {
    formParams.value.svadList.forEach((i, index) => {
      if (index === selectedIndex) {
        i.marCouponId = item.id
        i.couponName = item.couponName
        i.marCouponCount = item.couponCount
      }
    })
  }
}

function handleAddCoupons(type = false, row, selectedIndex = -1) {
  console.log(type, row, selectedIndex)
  couponListRef.value.init(type, row, selectedIndex)
}

/** 处理列表数据 */
function controlList(type, index) {
  if (type === 'add') {
    if (formParams.value.svadList?.length < 6) {
      formParams.value.svadList.push({
        id: formParams.value.svadList.length,
        type: 2,
        money: null,
        giftGold: null,
        activityTag: null,
        extraStoredTag: null,
        marCouponId: null,
        couponName: null,
        marCouponCount: null,
        isClick: false
      })
    }
  } else if (type === 'delete') {
    formParams.value.svadList.splice(index, 1)
  }
}

/**提交前校验数据 */
function handleCheck() {
  if (!formParams.value.svadList?.length) {
    ElMessage.warning('请设置储值金额')
    return false
  }
  return formParams.value.svadList.every((i) => {
    if (i.money?.length > 4 || i.giftGold?.length > 4) {
      ElMessage.warning('输入的数字不能大于9999')
      return false
    }
    if (+i.money < +i.giftGold) {
      ElMessage.warning('赠送金额不能超过对应的储值金额')
      return false
    }
    if ((i.money && +i.money <= 0) || (i.giftGold && +i.giftGold <= 0)) {
      ElMessage.warning('请输入大于0的正整数')
      return false
    }
    if (!i.money || !i.giftGold) {
      ElMessage.warning(`请输入${!i.money ? '储值金额' : '赠送金额'}`)
      return false
    }
    return true
  })
}

function handleSvadList() {
  let svadList = deepClone(formParams.value.svadList)
  // 首冲存在
  if (formParams.value.first.couponInfo || formParams.value.first?.credits) {
    svadList.push({
      type: 1,
      ...formParams.value.first.couponInfo,
      giftGold: formParams.value.first?.credits
    })
  }
  svadList = svadList.map((i) => {
    if (i?.giftGold && i?.money) {
      i.giftGold = +i?.giftGold
      i.money = +i?.money
    } else if (i?.giftGold) {
      i.giftGold = +i?.giftGold
    }
    return i
  })
  return svadList
}
/**提交 */
function handleAction(confirm) {
  if (confirm) {
    formRef.value.validate((valid) => {
      if (valid) {
        if (!handleCheck()) return
        const params = {
          name: formParams.value.name,
          remarks: formParams.value.remarks,
          activityImg: formParams.value.activityImg[0]?.url || formParams.value.activityImg,
          svadList: handleSvadList(),
          startTime: formParams.value.dateRange[0],
          endTime: formParams.value.dateRange[1]
        }
        console.log('新增数据', handleSvadList())
        postStoredAddApi(params).then(() => {
          proxy.$modal.msgSuccess(`${params.name}的储值活动添加成功`)
          onClose()
          emits('refreshList')
        })
      }
    })
  } else {
    onClose()
  }
}
function onClose() {
  visible.value = false
  formRef.value.resetFields()
  formParams.value = {
    name: null,
    remarks: null,
    activityImg: null,
    svadList: [],
    first: {
      credits: null,
      couponInfo: null
    },
    dateRange: []
  }
}
const emits = defineEmits(['refreshList'])
defineExpose({
  init
})
</script>
<style lang="scss" scoped>
.box {
  display: flex;
}
.title {
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 600;
}
.el-form-item__label {
  font-family:
    Helvetica Neue,
    Helvetica,
    PingFang SC,
    Hiragino Sans GB,
    Microsoft YaHei,
    Arial,
    sans-serif;
  height: 32px;
  line-height: 32px;
  font-weight: 700;
}
._line {
  margin: 0 0 10px 10px;
  // border-top: 1px solid #000;
  // padding: 20px 0 0;
}
.table-box {
  ::v-deep(.el-form-item--default) {
    margin-bottom: 0;
  }
}
</style>
